package core

import (
	"fengxueguang/noval-assistant/common"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	log "github.com/sirupsen/logrus"
	"path"
	"time"
)

func initLogger(logConfig *common.LogConfig) {
	// 设置是否显示文件名和行号
	log.SetReportCaller(logConfig.ShowFileLine)

	level, err := log.ParseLevel(logConfig.Level)
	if err != nil {
		level = log.ErrorLevel
	}
	log.SetLevel(level)

	// 设置日志输出到文件
	logFilePath := logConfig.FilePath
	logFileName := logConfig.FileName

	// 日志文件
	fileName := path.Join(logFilePath, logFileName)
	fileErrorName := path.Join(logFilePath, logConfig.FileErrorName)

	//// 写入文件
	//fileOut, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	//if err != nil {
	//	fmt.Println("err", err)
	//}
	//log.SetOutput(fileOut)

	// 设置 rotatelogs
	logWriter, err := rotatelogs.New(
		// 分割后的文件名称
		fileName+".%Y%m%d.log",
		// 生成软链，指向最新日志文件
		rotatelogs.WithLinkName(fileName),
		// 设置最大保存时间(7天)
		rotatelogs.WithMaxAge(time.Duration(logConfig.MaxAgeDay)*60*time.Hour),
		// 设置日志切割时间间隔(1天)
		rotatelogs.WithRotationTime(24*time.Hour),
		rotatelogs.WithRotationCount(uint(logConfig.MaxBackups)),
		rotatelogs.WithRotationSize(int64(logConfig.MaxSizeMb)*1024*1024),
	)

	logErrorWriter, err := rotatelogs.New(
		// 分割后的文件名称
		fileErrorName+".%Y%m%d.log",
		// 生成软链，指向最新日志文件
		rotatelogs.WithLinkName(fileErrorName),
		// 设置最大保存时间(7天)
		rotatelogs.WithMaxAge(time.Duration(logConfig.MaxAgeDay)*60*time.Hour),
		// 设置日志切割时间间隔(1天)
		rotatelogs.WithRotationTime(24*time.Hour),
		rotatelogs.WithRotationCount(uint(logConfig.MaxBackups)),
		rotatelogs.WithRotationSize(int64(logConfig.MaxSizeMb)*1024*1024),
	)

	//var logErrorWriter *(rotatelogs.RotateLogs)
	//logErrorWriter := logWriter
	//lowErrWriter
	//copyWriter(logErrWriter, logWriter)

	writeMap := lfshook.WriterMap{
		log.InfoLevel:  logWriter,
		log.FatalLevel: logWriter,
		log.DebugLevel: logWriter,
		log.WarnLevel:  logWriter,
		log.ErrorLevel: logErrorWriter,
		log.PanicLevel: logErrorWriter,
	}

	//log.SetFormatter(&log.TextFormatter{
	//	TimestampFormat: time.DateTime,
	//})
	lfHook := lfshook.NewHook(writeMap, &log.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05.999999999",
	})

	// 新增 Hook
	log.AddHook(lfHook)
}
